﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Collections;

public partial class TestPages_database : System.Web.UI.Page
{
    static bool initialized = false;

    private void initialize()
    {
        if (!initialized)
        {
            TextBox1.ReadOnly = true;
            TextBox2.ReadOnly = true;
            TextBox1.Text += (initialized = DatabaseManager.connectLocal()) ? "connected to " + DatabaseManager.DbName : "connection to database failed";
            TextBox1.Text += "\n";
            TextBox2.Text = "Results\n";
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        initialize();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {   
        System.Web.UI.HtmlControls.HtmlTextArea hta = (System.Web.UI.HtmlControls.HtmlTextArea)(form1.FindControl("TextArea1"));
        String sqlValue = hta.Value;
        TextBox1.Text += sqlValue + "\n";

        DatabaseManager.makeConnection();
        DatabaseManager.SqlCommand.CommandText = sqlValue;

        try
        {
            SqlDataReader sdr = DatabaseManager.SqlCommand.ExecuteReader();
            TextBox2.Text = "";
            TextBox2.Text += "Operation done!\n";
            showResults(readResults(sdr));
        }
        catch (Exception E) {
            TextBox2.Text += "Operation failed: " + DatabaseManager.SqlCommand + "\n";
            TextBox2.Text += E.Message + "\n";
        }
    }

    private ArrayList readResults(SqlDataReader dr)
    {
        String[] row = null;
        ArrayList results = new ArrayList();

        // reading data
        while (dr.Read())
        {
            if (row == null)
                row = new String[dr.FieldCount];

            for (int i = 0; i < dr.FieldCount; i++)
            {
                row[i] = (string)dr[i].ToString();
            }
            results.Add(row.Clone());
        }

        // close datareader
        dr.Close();
        return results;
    }

    private void showResults(ArrayList results)
    {
        foreach (object result in results)
        {
            foreach (string field in (string[])result)
                TextBox2.Text += field + "  |  ";
            
            TextBox2.Text += "\n";
        }
    }
}
